package yxy.game.pm2.active.module.openservicerank;

import org.joda.time.DateTime;
import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.actrushrankreward;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.active.module.ActType;
import yxy.game.pm2.active.module.ActiveModule_开服冲榜;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.rank.ActiveRushFutureHandle;
import yxy.game.pm2.active.module.rushtoptarget.CBTask;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.openserviceactive.OpenServiceRushRankHandle;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.union.UnionBean;

import java.util.*;

/**
 * <p>开服武将冲榜发奖励<p/>
 *
 * @ClassName OpenServiceRushFutureHandle
 * @Author jingtao-zheng
 * @Date 2022/7/8 17:49
 * @Version 1.0
 **/
public class OpenServiceHeroRushFutureHandle {
    private static final Logger logger = Logger.create(ActiveRushFutureHandle.class);
    private final static int HERO_COMPETITION = 1001;//武将比拼
    private final static int ARENA_HEGEMONY = 1002;//竞技争雄
    private final static int LEVEL_UP = 1003;//等级提升
    private final static int WORK_TOGETHER = 1004;//齐心协力

    public void heroupdate() {
        DateTime now = DateTime.now();
        //遍历所有区服
        for (AreaBean areaBean : AreaBean.all()) {
            //获取武将冲榜-活动控制信息
            activeControl sai = activeControl.get(areaBean.getAreaId(), ActType.开服武将冲榜);
            if (sai == null) {
                continue;
            }
            ArrayList<String> serverList = areaBean.getServerList();
            for (String serverId : serverList) {
                //获取开服冲榜-奖励发放信息
                OpenServiceRushModule module = OpenServiceRushModule.get(Integer.parseInt(serverId), sai);
                if (module == null) {
                    continue;
                }

                // 判断是否已经领取奖励
                if (module.isAward()) {
                    continue;
                }
                //如果没有领取奖励,获取奖励类型去发奖
                int type = module.getRewardtype();
                //发奖
                lssueReward(module, areaBean, type, now);
            }
        }
    }

    public void areanupdate() {
        DateTime now = DateTime.now();
        //遍历所有区服
        for (AreaBean areaBean : AreaBean.all()) {
            //获取武将冲榜-活动控制信息
            activeControl sai = activeControl.get(areaBean.getAreaId(), ActType.开服竞技场冲榜);
            if (sai == null) {
                continue;
            }
            ArrayList<String> serverList = areaBean.getServerList();
            for (String serverId : serverList) {
                //获取开服冲榜-奖励发放信息
                OpenServiceRushModule module = OpenServiceRushModule.get(Integer.parseInt(serverId), sai);
                if (module == null) {
                    continue;
                }

                // 判断是否已经领取奖励
                if (module.isAward()) {
                    continue;
                }
                //如果没有领取奖励,获取奖励类型去发奖
                int type = module.getRewardtype();
                //发奖
                lssueReward(module, areaBean, type, now);
            }
        }
    }

    public void levelupdate() {
        DateTime now = DateTime.now();
        //遍历所有区服
        for (AreaBean areaBean : AreaBean.all()) {
            //获取武将冲榜-活动控制信息
            activeControl sai = activeControl.get(areaBean.getAreaId(), ActType.开服等级冲榜);
            if (sai == null) {
                continue;
            }
            ArrayList<String> serverList = areaBean.getServerList();
            for (String serverId : serverList) {
                //获取开服冲榜-奖励发放信息
                OpenServiceRushModule module = OpenServiceRushModule.get(Integer.parseInt(serverId), sai);
                if (module == null) {
                    continue;
                }

                // 判断是否已经领取奖励
                if (module.isAward()) {
                    continue;
                }
                //如果没有领取奖励,获取奖励类型去发奖
                int type = module.getRewardtype();
                //发奖
                lssueReward(module, areaBean, type, now);
            }
        }
    }

    public void boosupdate() {
        DateTime now = DateTime.now();
        //遍历所有区服
        for (AreaBean areaBean : AreaBean.all()) {
            //获取武将冲榜-活动控制信息
            activeControl sai = activeControl.get(areaBean.getAreaId(), ActType.开服联盟boos冲榜);
            if (sai == null) {
                continue;
            }
            ArrayList<String> serverList = areaBean.getServerList();
            for (String serverId : serverList) {
                //获取开服冲榜-奖励发放信息
                OpenServiceRushModule module = OpenServiceRushModule.get(Integer.parseInt(serverId), sai);
                if (module == null) {
                    continue;
                }

                // 判断是否已经领取奖励
                if (module.isAward()) {
                    continue;
                }
                //如果没有领取奖励,获取奖励类型去发奖
                int type = module.getRewardtype();
                //发奖
                lssueRewardBoos(module, areaBean, type, now);
            }
        }
    }

    /**
     * 发奖
     * 发奖条件
     * 1.当前时间晚于活动结束时间
     * 2.奖励还未发放(之前已经判断过了,这里不用再判断)
     */
//    private void lssueReward(OpenServiceRushModule module, AreaBean areaBean, int type, DateTime now) {
//        DateTime endTime = module.getRewardTime();
//        if (endTime.isAfter(now)) {
//            return;
//        }
//
//        //缓存拿策划配置的奖励信息
//        Map<String, actrushrankreward> all = ActDataCenter.getAllData(actrushrankreward.class,
//                areaBean.getAreaId());
//        for (actrushrankreward rankdata : all.values()) {
//            int group = rankdata.getGroup();
//            if (!matchReward(type, group)) {//匹配排行榜奖励
//                continue;
//            }
//            //从排行榜获取数据
//            Collection<RankEntry> rankEntries = OpenServiceRushRankHandle.range(areaBean.getAreaId(), type,
//                    rankdata.getRankingmin(), rankdata.getRankingmax());
//
//
//            Collection<Currency> rewards = Currency.create(rankdata.getRewardtype(), rankdata.getRewardid(), rankdata.getRewardnum());
//            Collection<Currency> brotherRewards = null;
//            if (type == 1004) {
//                //联盟boos特殊处理
//                brotherRewards = Currency.create(rankdata.getMemberrewardtype(), rankdata.getMemberrewardid(), rankdata.getMemberrewardnum());
//            }
//            int rank = rankdata.getRankingmin();
//
//            for (RankEntry entry : rankEntries) {
//                String playerCode = entry.getKey();
//
//
//                String title = getTitle(type);
//                String content = getMsg(type, rank);
//                String UnionCode = entry.getKey();
//                if (type == 1004) {
//                    UnionBean unionBean = UnionBean.get(UnionCode);
//                    String leader = unionBean.getLeader();
//                    // 盟主发邮件
//                    new MailHandle().sendMail(leader, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, rewards);
//                } else {
//                    new MailHandle().sendMail(playerCode, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, rewards);
//                }
//                //获取该盟主的所有盟友
//                if (null != brotherRewards) {
//                    UnionBean unionBean = UnionBean.get(UnionCode);
//                    ArrayList<String> memberList = unionBean.getMemberList();
//                    ArrayList<String> viceList = unionBean.getViceList();
//                    ArrayList<String> list = new ArrayList<>();
//                    if (null != memberList && memberList.size() != 0) {
//                        list.addAll(memberList);
//                    }
//                    if (null != viceList && viceList.size() != 0) {
//                        list.addAll(viceList);
//                    }
//                    for (String brotherplayerCode : list) {
//                        new MailHandle().sendMail(brotherplayerCode, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, brotherRewards);
//                        PlayerBean playerBean2 = PlayerBean.get(brotherplayerCode);
//                        logger.info(areaBean.getAreaId() + "区开服冲榜" + type + "排名奖励了发完了！！！！" + DateTime.now().toString() + "盟友" + playerBean2.getName());
//                    }
//                }
//                logger.info(areaBean.getAreaId() + "区开服冲榜" + type + "排名奖励了发完了！！！！" + DateTime.now().toString());
//                rank++;
//            }
//
//        }
//        //更新领取信息
//        module.setAward(true);
//        module.set();
//        //打个日志记录
//        logger.info(areaBean.getAreaId() + "区开服冲榜" + type + "排名奖励了发完了！！！！" + DateTime.now().toString());
//    }

    private void lssueReward(OpenServiceRushModule module, AreaBean areaBean, int type, DateTime now) {
        DateTime endTime = module.getRewardTime();
        if (endTime.isAfter(now)) {
            return;
        }
        //更新领取信息
        module.setAward(true);
        module.set();
        //缓存拿策划配置的奖励信息
        Map<String, actrushrankreward> all = ActDataCenter.getAllData(actrushrankreward.class,
                areaBean.getAreaId());
        for (actrushrankreward rankdata : all.values()) {
            int group = rankdata.getGroup();
            if (!matchReward(type, group)) {//匹配排行榜奖励
                continue;
            }
            //从排行榜获取数据
            Collection<RankEntry> rankEntries = OpenServiceRushRankHandle.range(areaBean.getAreaId(), type,
                    rankdata.getRankingmin(), rankdata.getRankingmax());
            Collection<Currency> rewards = Currency.create(rankdata.getRewardtype(), rankdata.getRewardid(), rankdata.getRewardnum());

            int rank = rankdata.getRankingmin();
            for (RankEntry entry : rankEntries) {
                String playerCode = entry.getKey();
                //获取领奖领奖条件
                int needtask = rankdata.getNeedtask();
                if (needtask != 0) {
                    ActiveModule_开服冲榜 am = ActiveModule_开服冲榜.get(playerCode,type);
                    //最多递归3次
                    actrushrankreward actrushrankreward = matchReward(needtask, all.values(), am, 3);
                    rewards = Currency.create(actrushrankreward.getRewardtype(), actrushrankreward.getRewardid(), actrushrankreward.getRewardnum());
                }
                String title = getTitle(type);
                String content = getMsg(type, rank);
                new MailHandle().sendMail(playerCode, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, rewards);
                rank++;
            }
        }
    }


    private actrushrankreward matchReward(int needtask, Collection<actrushrankreward> actrushrankrewards, ActiveModule_开服冲榜 am, int num){
        if(num<=0){
            return null;
        }
        //获取条件信息
        Optional<actrushrankreward> actrushrankrewardfirst = actrushrankrewards
                .stream()
                .filter(_actrushrankreward -> _actrushrankreward.getNeedtask() == needtask)
                .findFirst();
        actrushrankreward actrushrankreward = actrushrankrewardfirst.get();
        Optional<CBTask> first = am.getIdtaskcode()
                .values()
                .stream()
                .filter(_CBTask -> _CBTask.getTaskid() == needtask)
                .findFirst();
        CBTask cbTask = first.get();
        //获取玩家该任务完成信息
        Task task = Task.get(am.getPlayerCode(), cbTask.getTaskcode());//通过TaskCode获取玩家单个任务的详细信息
        boolean finish = task.isFinish();
        if(finish){
            return actrushrankreward;
        }
        //没完成就顺延下一个条件,看是否完成
        Optional<yxy.cherry.data.bean.actrushrankreward> isactrushrankreward =actrushrankrewards
                .stream()
                .filter(_actrushrankreward -> _actrushrankreward.getId() == (actrushrankreward.getId() + 1))
                .findFirst();
        yxy.cherry.data.bean.actrushrankreward actrushrankreward2 = isactrushrankreward.get();
        int needtask1 = actrushrankreward2.getNeedtask();
        if(needtask1 == 0){
            return actrushrankreward2;
        }
        return matchReward(needtask1,actrushrankrewards,am,--num);
    }


    /**
     * 联盟boos发奖,因为特殊,所以单独处理
     */
    private void lssueRewardBoos(OpenServiceRushModule module, AreaBean areaBean, int type, DateTime now) {
        DateTime endTime = module.getRewardTime();
        if (endTime.isAfter(now)) {
            return;
        }
        //更新领取信息
        module.setAward(true);
        module.set();
        //缓存拿策划配置的奖励信息
        Map<String, actrushrankreward> all = ActDataCenter.getAllData(actrushrankreward.class,
                areaBean.getAreaId());
        for (actrushrankreward rankdata : all.values()) {
            int group = rankdata.getGroup();
            if (!matchReward(type, group)) {//匹配排行榜奖励
                continue;
            }
            //从排行榜获取数据
            Collection<RankEntry> rankEntries = OpenServiceRushRankHandle.range(areaBean.getAreaId(), type,
                    rankdata.getRankingmin(), rankdata.getRankingmax());


            Collection<Currency> rewards = Currency.create(rankdata.getRewardtype(), rankdata.getRewardid(), rankdata.getRewardnum());
            Collection<Currency> brotherRewards = Currency.create(rankdata.getMemberrewardtype(), rankdata.getMemberrewardid(), rankdata.getMemberrewardnum());

            int rank = rankdata.getRankingmin();
            for (RankEntry entry : rankEntries) {
                String UnionCode = entry.getKey();
                UnionBean unionBean = UnionBean.get(UnionCode);
                String leader = unionBean.getLeader();
                //获取领奖领奖条件
                int needtask = rankdata.getNeedtask();
                if (needtask != 0) {
                    ActiveModule_开服冲榜 am = ActiveModule_开服冲榜.get(leader,type);
                    //最多递归3次
                    actrushrankreward actrushrankreward = matchReward(needtask, all.values(), am, 3);
                    rewards = Currency.create(actrushrankreward.getRewardtype(), actrushrankreward.getRewardid(), actrushrankreward.getRewardnum());
                    brotherRewards = Currency.create(actrushrankreward.getMemberrewardtype(), actrushrankreward.getMemberrewardid(), actrushrankreward.getMemberrewardnum());
                }

                String title = getTitle(type);
                String content = getMsg(type, rank);


                // 盟主发邮件
                new MailHandle().sendMail(leader, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, rewards);
                //获取该盟主的所有盟友
                if (null != brotherRewards) {

                    ArrayList<String> memberList = unionBean.getMemberList();
                    ArrayList<String> viceList = unionBean.getViceList();
                    ArrayList<String> list = new ArrayList<>();
                    if (null != memberList && memberList.size() != 0) {
                        list.addAll(memberList);
                    }
                    if (null != viceList && viceList.size() != 0) {
                        list.addAll(viceList);
                    }
                    //联盟成员去重
                    Set<String> set = new HashSet();
                    set.addAll(list);
                    for (String brotherplayerCode : set) {
                        new MailHandle().sendMail(brotherplayerCode, MailTypeEnum.Mail, title, content, CCReason.活动_开服冲榜, brotherRewards);
                    }
                }
                rank++;
            }

        }
    }

    private String getTitle(int type) {
        if (type == HERO_COMPETITION) {
            return GameString.开服冲榜武将比拼奖励_title().getText();
        }

        if (type == ARENA_HEGEMONY) {
            return GameString.开服冲榜竞技争雄奖励_title().getText();
        }
        if (type == LEVEL_UP) {
            return GameString.开服冲榜等级提升奖励_title().getText();
        }
        if (type == WORK_TOGETHER) {
            return GameString.开服冲榜齐心协力奖励_title().getText();
        }
        return "";
    }

    private String getMsg(int type, int rank) {
        if (type == HERO_COMPETITION) {
            return GameString.开服冲榜武将比拼奖励_msg(rank).getText();
        }
        if (type == ARENA_HEGEMONY) {
            return GameString.开服冲榜竞技争雄奖励_msg(rank).getText();
        }
        if (type == LEVEL_UP) {
            return GameString.开服冲榜等级提升奖励_msg(rank).getText();
        }
        if (type == WORK_TOGETHER) {
            return GameString.开服冲榜齐心协力奖励_msg(rank).getText();
        }
        return "";
    }

    private boolean matchReward(int type, int group) {
        if (type == HERO_COMPETITION && group == 1) {
            return true;
        }
        if (type == ARENA_HEGEMONY && group == 2) {
            return true;
        }
        if (type == LEVEL_UP && group == 3) {
            return true;
        }
        if (type == WORK_TOGETHER && group == 4) {
            return true;
        }
        return false;
    }
}
